package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Richard
 * Date: 04/02/13
 * Time: 00:21
 * To change this template use File | Settings | File Templates.
 */
public class Login {
    public InOut inOut;
    public List<User> users = new ArrayList<User>();
    public User currentUser;
    public MenuCallback menuCallback;
    public boolean loggedIn = false;

    private int attemptNumber = 1;

    public Login(InOut _inOut) {
        inOut = _inOut;
    }

    public void start() {
        displayEnterUsernameMessage();
        readUsername();
    }

    public void logout() {
        loggedIn = false;
    }

    public void displayEnterUsernameMessage() {
        inOut.println("Please enter your username, or [0] to return to the previous menu");
    }

    public boolean checkUsername(String username) {
        for (User user : users) {
            if (user.username.equals(username)) {
                currentUser = user;
                return true;
            }
        }
        return false;
    }

    public void readUsername() {
        String input = inOut.readNextLine();
        if (input.equals("0"))
            menuCallback.Invoke();
        else if (checkUsername(input)) {
            inOut.println("Please enter your password");
            readPassword();
        }
        else {
            inOut.println("Invalid username. Please re-enter or [0] to return to the previous menu");
            readUsername();
        }
    }

    public void readPassword() {
        String input = inOut.readNextLine();
        boolean success = false;
        if (currentUser != null)
            success = currentUser.checkPassword(input);
        if (success) {
            inOut.println("Thank you. You are now logged in.");
            loggedIn = true;
            menuCallback.Invoke();
        }
        else if (attemptNumber < 3) {
            inOut.println("Attempt " + attemptNumber + "/3: invalid password. Please try again.");
            attemptNumber++;
            readPassword();
        }
        else {
            inOut.println("Attempt 3/3: invalid password. Returning to Home menu.");
            menuCallback.Invoke();
        }
    }
}
